﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml;
using cz.uhul.DSMLv2;


namespace cz.uhul.DSMLv2.Server.Sql
{



  public static partial class LdRequestServerExtension
  {

    public struct EntryNfo
    {
      public string DN;
      public Guid DnKey;
      public bool IsDirty;
      public Guid ClassDnKey;
      public bool IsInstance;
    }

    public struct AttrNfo
    {
      public string AttrName;
      public Guid AttrDnKey;
      public Guid DefiningClassKey;
      public bool IsInstance;
      public bool IsSingleValue;
      public bool IsMust;
      public string Syntax;
      
    }



    public static bool Fill(this LdEntry ent, LdAttrNameCollection reqAttrs, bool TypesOnly, Guid DnKey)
    {

      EntryNfo enfo = LdDatabase.GetEntryNfo(null, DnKey);

      if (enfo.IsDirty)
        return false;

      ent.DistinguishedName = enfo.DN;
      ent.DnKey = enfo.DnKey;

      //todo:resolve objectClass

      //resolve attributes
      //get available from LD
      List<string> attrs = LdDatabase.GetAttributeNames(enfo.DN);

      //List<LdAttrName> tmp;
      List<string> tmp;

      if (reqAttrs.Count > 0)
        //tmp = reqAttrs.Where(p => attrs.Contains(p.Name)).ToList<LdAttrName>();
        tmp = attrs.Where(p => reqAttrs.Select(N => N.Name).Contains(p)).ToList<string>();

      else
        tmp = attrs;

      foreach (string attr in tmp)
      {
        LdAttr objAttr = new LdAttr() { Name = attr };
        List<string> vals = null;

        try
        {
          vals = LdDatabase.GetRelations(enfo.DN, attr);
        }
        catch {}

        if (vals.Count > 0 && !TypesOnly)
          foreach(string val in vals)
            objAttr.Values.Add(val);
          
        ent.Attributes.Add(objAttr);

      }

      return true;

    }





  }

}